import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import { KLineData, KLineQuery, TimeshareRecord } from '../types';
import { Card, Select, Spin, message, Divider, Table, Tag } from 'antd';
import { WeightAPI } from '../services/api';

const { Option } = Select;

interface KLineChartProps {
  height?: number;
  className?: string;
  refreshTrigger?: number; // 添加刷新触发器
}

const KLineChart: React.FC<KLineChartProps> = ({ height = 500, className, refreshTrigger }) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);
  const [loading, setLoading] = useState(true);
  const [period, setPeriod] = useState<'day' | 'week' | 'month' | 'year'>('day');
  const [klineData, setKlineData] = useState<KLineData[]>([]);
  const [selectedDate, setSelectedDate] = useState<string>('');
  const [timeshareData, setTimeshareData] = useState<TimeshareRecord[]>([]);

  // 加载分时数据
  const loadTimeshareData = async (date: string) => {
    try {
      const response = await WeightAPI.getTimeshareData(date);
      if (response.success && response.data) {
        setTimeshareData(response.data.records);
      } else {
        setTimeshareData([]);
        message.warning(`暂无 ${date} 的分时数据`);
      }
    } catch (error) {
      console.error('获取分时数据失败:', error);
      setTimeshareData([]);
      message.error('获取分时数据失败');
    }
  };

  // 初始化图表
  const initChart = () => {
    if (!chartRef.current) return;

    // 销毁已存在的图表实例
    if (chartInstance.current) {
      chartInstance.current.dispose();
    }

    // 创建新的图表实例
    chartInstance.current = echarts.init(chartRef.current, 'dark');
    
    // 设置图表配置
    const option = getChartOption();
    chartInstance.current.setOption(option);
    
    // 添加点击事件监听
    chartInstance.current.on('click', (params: any) => {
      if (params.componentType === 'series' && params.seriesType === 'candlestick') {
        const clickedDate = params.name; // 使用params.name获取日期，这是x轴的值
        if (clickedDate) {
          console.log('点击了蜡烛图，日期:', clickedDate);
          // 将MM-DD格式转换为YYYY-MM-DD格式
          const currentYear = new Date().getFullYear();
          const fullDate = `${currentYear}-${clickedDate}`;
          console.log('转换后的完整日期:', fullDate);
          setSelectedDate(clickedDate);
          loadTimeshareData(fullDate);
        }
      }
    });

    // 监听窗口大小变化
    const handleResize = () => {
      chartInstance.current?.resize();
    };
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  };

  // 计算移动平均线
  const calculateMA = (data: KLineData[], period: number) => {
    const result: number[] = [];
    for (let i = 0; i < data.length; i++) {
      if (i < period - 1) {
        result[i] = data[i].close; // 前面不足周期的数据使用当前收盘价
      } else {
        let sum = 0;
        for (let j = i - period + 1; j <= i; j++) {
          sum += data[j].close; // 使用收盘价计算MA
        }
        result[i] = sum / period;
      }
    }
    return result;
  };

  // 获取图表配置
  const getChartOption = () => {
    const dates = klineData.map(item => {
      const date = new Date(item.date);
      return `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    });
    // 确保蜡烛图数据格式正确：[open, close, low, high]
    const candlestickData = klineData.map(item => [item.open, item.close, item.low, item.high]);
    const volumeData = klineData.map(item => item.volume);
    
    // 计算不同周期的移动平均线
    const ma5Data = calculateMA(klineData, 5);
    const ma10Data = calculateMA(klineData, 10);
    const ma20Data = calculateMA(klineData, 20);

    return {
      backgroundColor: '#0a0e1b',
      animation: false,
      grid: [
        {
          left: '8%',
          right: '3%',
          top: '8%',
          height: '60%'
        },
        {
          left: '8%',
          right: '3%',
          top: '73%',
          height: '15%'
        }
      ],
      xAxis: [
        {
          type: 'category',
          data: dates,
          boundaryGap: false,
          axisLine: { onZero: false, lineStyle: { color: '#777' } },
          splitLine: { show: false },
          axisLabel: { color: '#999' }
        },
        {
          type: 'category',
          gridIndex: 1,
          data: dates,
          boundaryGap: false,
          axisLine: { onZero: false, lineStyle: { color: '#777' } },
          axisTick: { show: false },
          splitLine: { show: false },
          axisLabel: { show: false }
        }
      ],
      yAxis: [
        {
          scale: false, // 不自动缩放
          splitArea: { show: false },
          splitLine: { lineStyle: { color: '#333' } },
          axisLine: { lineStyle: { color: '#777' } },
          axisLabel: { 
            color: '#999',
            formatter: (value: number) => `${value.toFixed(1)}kg` // 直接显示真实体重
          },
          min: function(value: any) {
            // 计算实际体重范围
            const realMin = value.min; // 实际最轻体重
            const realMax = value.max; // 实际最重体重
            const rangeMin = Math.floor(realMin) - 0.5; // 向下取整减0.5kg
            return rangeMin;
          },
          max: function(value: any) {
            const realMin = value.min;
            const realMax = value.max; 
            const rangeMax = Math.ceil(realMax) + 0.5; // 向上取整加0.5kg
            return rangeMax;
          },
          interval: 0.5 // 每0.5kg一个刻度
        },
        {
          scale: true,
          gridIndex: 1,
          splitNumber: 2,
          axisLabel: { show: false },
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: { show: false }
        }
      ],
      dataZoom: [
        {
          type: 'inside',
          xAxisIndex: [0, 1],
          start: 0,
          end: 100,
          zoomOnMouseWheel: true,
          moveOnMouseMove: true,
          moveOnMouseWheel: true
        },
        {
          show: true,
          type: 'slider',
          xAxisIndex: [0, 1],
          bottom: 10,
          start: 0,
          end: 100,
          height: 25,
          backgroundColor: '#1a1a2e',
          borderColor: '#2d4a6b',
          fillerColor: 'rgba(45, 74, 107, 0.3)',
          handleStyle: {
            color: '#00da3c',
            borderColor: '#00da3c'
          },
          textStyle: {
            color: '#999',
            fontSize: 10
          },
          dataBackground: {
            lineStyle: {
              color: '#2d4a6b',
              width: 1
            },
            areaStyle: {
              color: 'rgba(45, 74, 107, 0.2)'
            }
          },
          selectedDataBackground: {
            lineStyle: {
              color: '#00da3c',
              width: 1
            },
            areaStyle: {
              color: 'rgba(0, 218, 60, 0.3)'
            }
          }
        }
      ],
      series: [
        {
          name: '体重K线',
          type: 'candlestick',
          data: candlestickData,
          itemStyle: {
            // 体重下降=K线上涨（绿色），体重上升=K线下跌（红色）
            color: '#00da3c', // 上涨（体重下降）绿色实体
            color0: '#ec0000', // 下跌（体重上升）红色实体
            borderColor: '#00da3c', // 上涨时的影线颜色
            borderColor0: '#ec0000', // 下跌时的影线颜色
            borderWidth: 1, // 影线宽度
            shadowBlur: 3,
            shadowColor: 'rgba(0,0,0,0.3)'
          },
          // 确保显示完整的蜡烛图
          barWidth: '70%',
          barMaxWidth: 20,
          // 添加渐变效果
          emphasis: {
            itemStyle: {
              borderWidth: 2,
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0,0,0,0.5)'
            }
          }
        },
        {
          name: '记录次数',
          type: 'bar',
          xAxisIndex: 1,
          yAxisIndex: 1,
          data: volumeData,
          itemStyle: {
            color: function(params: any) {
              const index = params.dataIndex;
              const current = candlestickData[index];
              if (current) {
                const isUp = current[1] < current[0]; // 体重下降=上涨（绿色）
                return {
                  type: 'linear',
                  x: 0, y: 0, x2: 0, y2: 1,
                  colorStops: [
                    { offset: 0, color: isUp ? '#00da3c' : '#ec0000' },
                    { offset: 1, color: isUp ? 'rgba(0,218,60,0.3)' : 'rgba(236,0,0,0.3)' }
                  ]
                };
              }
              return '#666';
            },
            borderRadius: [2, 2, 0, 0]
          }
        },
        // MA5 移动平均线
        {
          name: 'MA5',
          type: 'line',
          data: ma5Data,
          smooth: false,
          lineStyle: {
            width: 1,
            color: '#f39800'
          },
          showSymbol: false,
          emphasis: {
            focus: 'series'
          }
        },
        // MA10 移动平均线
        {
          name: 'MA10',
          type: 'line',
          data: ma10Data,
          smooth: false,
          lineStyle: {
            width: 1,
            color: '#1890ff'
          },
          showSymbol: false,
          emphasis: {
            focus: 'series'
          }
        },
        // MA20 移动平均线
        {
          name: 'MA20',
          type: 'line',
          data: ma20Data,
          smooth: false,
          lineStyle: {
            width: 1,
            color: '#722ed1'
          },
          showSymbol: false,
          emphasis: {
            focus: 'series'
          }
        }
      ],
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        backgroundColor: '#1a1a1a',
        borderColor: '#555',
        textStyle: { color: '#fff' },
        formatter: function(params: any[]) {
          const candlestick = params.find(p => p.seriesName === '体重K线');
          const volume = params.find(p => p.seriesName === '记录次数');
          
          if (!candlestick) return '';
          
          const data = candlestick.data;
          // 直接显示真实体重，不需要反转
          const realOpen = data[0].toFixed(1);
          const realClose = data[1].toFixed(1);
          const realHigh = data[3].toFixed(1);  // data[3]是high
          const realLow = data[2].toFixed(1);   // data[2]是low
          
          return `
            <div style="padding: 5px;">
              <div style="font-weight: bold; margin-bottom: 5px;">${candlestick.axisValue}</div>
              <div>开盘: ${realOpen}kg</div>
              <div>收盘: ${realClose}kg</div>
              <div>最低: ${realLow}kg</div>
              <div>最高: ${realHigh}kg</div>
              ${volume ? `<div>记录: ${volume.data}次</div>` : ''}
            </div>
          `;
        }
      }
    };
  };

  // 加载K线数据
  const loadKLineData = async () => {
    setLoading(true);
    try {
      const query: KLineQuery = { period, limit: 100 };
      const response = await WeightAPI.getKLineData(query);
      
      if (response.success && response.data) {
        setKlineData(response.data.kline);
      } else {
        message.error(response.error || '获取K线数据失败');
      }
    } catch (error: any) {
      message.error(error.error || '网络错误');
    } finally {
      setLoading(false);
    }
  };

  // 更新图表数据
  useEffect(() => {
    if (chartInstance.current && klineData.length > 0) {
      const option = getChartOption();
      chartInstance.current.setOption(option);
    }
  }, [klineData]);

  // 监听刷新触发器，当有新数据时自动刷新
  useEffect(() => {
    if (refreshTrigger && refreshTrigger > 0) {
      loadKLineData();
    }
  }, [refreshTrigger]);

  // 初始化和周期变更
  useEffect(() => {
    loadKLineData();
  }, [period]);

  // 初始化图表
  useEffect(() => {
    const cleanup = initChart();
    
    // 添加ResizeObserver来监听容器大小变化
    let resizeObserver: ResizeObserver | null = null;
    if (chartRef.current) {
      resizeObserver = new ResizeObserver(() => {
        if (chartInstance.current) {
          chartInstance.current.resize();
        }
      });
      resizeObserver.observe(chartRef.current);
    }
    
    return () => {
      cleanup?.();
      if (resizeObserver) {
        resizeObserver.disconnect();
      }
    };
  }, []);

  return (
    <div className="kline-container">
      <div style={{ 
        padding: '16px 20px 12px',
        borderBottom: '1px solid #2d4a6b',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: '20px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
            <span style={{ color: '#fff', fontSize: '18px', fontWeight: 'bold' }}>
              体重指数 WEIGHT
            </span>
            
            {/* 当前价格信息 */}
            {klineData.length > 0 && (
              <>
                <span style={{ 
                  color: klineData[klineData.length - 1]?.close < klineData[klineData.length - 1]?.open ? '#00da3c' : '#ec0000', 
                  fontSize: '22px', 
                  fontWeight: 'bold',
                  fontFamily: 'monospace'
                }}>
                  {klineData[klineData.length - 1]?.close.toFixed(1)}
                </span>
                <span style={{ 
                  color: klineData[klineData.length - 1]?.close < klineData[klineData.length - 1]?.open ? '#00da3c' : '#ec0000',
                  fontSize: '14px'
                }}>
                  {klineData[klineData.length - 1]?.close < klineData[klineData.length - 1]?.open ? '-' : '+'}
                  {Math.abs((klineData[klineData.length - 1]?.close || 0) - (klineData[klineData.length - 1]?.open || 0)).toFixed(2)}
                </span>
                <span style={{ 
                  color: klineData[klineData.length - 1]?.close < klineData[klineData.length - 1]?.open ? '#00da3c' : '#ec0000',
                  fontSize: '14px'
                }}>
                  {(() => {
                    const close = klineData[klineData.length - 1]?.close || 0;
                    const open = klineData[klineData.length - 1]?.open || 1;
                    const change = Math.abs(close - open);
                    const percentage = (change / open) * 100;
                    return `${klineData[klineData.length - 1]?.close < klineData[klineData.length - 1]?.open ? '-' : '+'}${percentage.toFixed(2)}%`;
                  })()}
                </span>
                
                <div style={{ 
                  fontSize: '12px', 
                  color: '#999',
                  display: 'flex',
                  gap: '12px',
                  marginLeft: '20px'
                }}>
                  <span>最高 <span style={{color: '#ec0000'}}>{Math.max(...klineData.map(d => d.high)).toFixed(1)}</span></span>
                  <span>最低 <span style={{color: '#00da3c'}}>{Math.min(...klineData.map(d => d.low)).toFixed(1)}</span></span>
                  <span>记录 <span style={{color: '#1890ff'}}>{klineData[klineData.length - 1]?.volume || 0}</span></span>
                </div>
              </>
            )}
          </div>
          
          <div className="ma-legend">
            <div className="ma-item">
              <div className="ma-color-dot" style={{ backgroundColor: '#f39800' }}></div>
              <span style={{ color: '#f39800' }}>MA5</span>
            </div>
            <div className="ma-item">
              <div className="ma-color-dot" style={{ backgroundColor: '#1890ff' }}></div>
              <span style={{ color: '#1890ff' }}>MA10</span>
            </div>
            <div className="ma-item">
              <div className="ma-color-dot" style={{ backgroundColor: '#722ed1' }}></div>
              <span style={{ color: '#722ed1' }}>MA20</span>
            </div>
          </div>
        </div>
        
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          {/* 专业股票软件风格的时间选择器 */}
          <div style={{ display: 'flex', backgroundColor: '#2a2a3e', borderRadius: '4px', padding: '2px' }}>
            {[
              { key: 'day', label: '分时', active: false },
              { key: 'day', label: '日K', active: period === 'day' },
              { key: 'week', label: '周K', active: period === 'week' },
              { key: 'month', label: '月K', active: period === 'month' },
              { key: 'year', label: '年K', active: period === 'year' }
            ].map((item, index) => (
              <div
                key={index}
                onClick={() => setPeriod(item.key as any)}
                style={{
                  padding: '4px 8px',
                  fontSize: '12px',
                  cursor: 'pointer',
                  backgroundColor: item.active ? '#00da3c' : 'transparent',
                  color: item.active ? '#000' : '#fff',
                  borderRadius: '2px',
                  transition: 'all 0.2s'
                }}
              >
                {item.label}
              </div>
            ))}
          </div>
        </div>
      </div>
      <Spin spinning={loading}>
        <div 
          ref={chartRef} 
          style={{ 
            width: '100%', 
            height: '600px',
            backgroundColor: '#0a0e1b',
            minHeight: '500px'
          }} 
        />
      </Spin>
      
      {/* 分时数据显示 */}
      {selectedDate && (
        <>
          <Divider style={{ margin: '16px 0', borderColor: '#2d4a6b' }} />
          <div style={{ padding: '0 20px 16px' }}>
            <div style={{ 
              display: 'flex', 
              alignItems: 'center', 
              marginBottom: '12px',
              gap: '8px'
            }}>
              <span style={{ color: '#fff', fontSize: '14px', fontWeight: 'bold' }}>
                📊 {selectedDate} 分时数据
              </span>
              <Tag color="#00da3c" style={{ margin: 0 }}>
                共 {timeshareData.length} 条记录
              </Tag>
            </div>
            
            {timeshareData.length > 0 ? (
              <Table
                dataSource={timeshareData.map((item, index) => ({ ...item, key: index }))}
                size="small"
                pagination={false}
                style={{ backgroundColor: 'rgba(26, 26, 46, 0.5)' }}
                columns={[
                  {
                    title: '时间',
                    dataIndex: 'time',
                    key: 'time',
                    width: 80,
                    render: (time) => (
                      <span style={{ color: '#1890ff', fontSize: '12px' }}>
                        {time}
                      </span>
                    )
                  },
                  {
                    title: '体重',
                    dataIndex: 'weight',
                    key: 'weight',
                    width: 80,
                    render: (weight) => (
                      <span style={{ color: '#00da3c', fontWeight: 'bold' }}>
                        {weight}kg
                      </span>
                    )
                  },
                  {
                    title: '类型',
                    dataIndex: 'record_type',
                    key: 'record_type',
                    width: 80,
                    render: (type) => {
                      const typeMap = {
                        morning: { label: '🌅 早晨', color: '#f39800' },
                        evening: { label: '🌙 晚上', color: '#722ed1' },
                        anytime: { label: '⏰ 随时', color: '#1890ff' }
                      };
                      const info = typeMap[type as keyof typeof typeMap] || { label: type, color: '#999' };
                      return (
                        <Tag color={info.color} style={{ margin: 0, fontSize: '11px' }}>
                          {info.label}
                        </Tag>
                      );
                    }
                  },
                  {
                    title: '备注',
                    dataIndex: 'note',
                    key: 'note',
                    render: (note) => (
                      <span style={{ color: '#999', fontSize: '12px' }}>
                        {note || '-'}
                      </span>
                    )
                  }
                ]}
              />
            ) : (
              <div style={{ 
                padding: '20px', 
                textAlign: 'center', 
                color: '#999',
                backgroundColor: 'rgba(26, 26, 46, 0.5)',
                borderRadius: '4px'
              }}>
                暂无该日期的体重记录
              </div>
            )}
          </div>
        </>
      )}
    </div>
  );
};

export default KLineChart;
